package cn.aran.basic.interceptor;

import cn.aran.basic.annotation.PreAuthorize;
import cn.aran.basic.jwt.JwtUtils;
import cn.aran.basic.jwt.Payload;
import cn.aran.basic.jwt.RsaUtils;
import cn.aran.basic.jwt.Userinfo;
import cn.aran.sys.mapper.PermissionMapper;
import cn.aran.user.domain.Logininfo;
import cn.aran.user.domain.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pub}")
    private String  jwtRsaPub;

    /**
     * @Title: preHandle
     * @Description: 无状态token拦截器
     * @Author: Aran
     * @Version: 1.0
     * @Date:  2022/7/14 18:10
     * @Parameters: [request, response, handler]
     * @Return boolean
     */
    /* @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("3333333333");
        // 获取请求头的消息token
        String token = request.getHeader("token");
        // 判断token是否为空且是否正确
        if (token != null){
            Object logininfo = redisTemplate.opsForValue().get(token);
            if (logininfo != null){
                // 判断登录用户是否有权限
                Logininfo logininfoTem = new Logininfo();
                BeanUtils.copyProperties(logininfo, logininfoTem);
                // 判断是否是员工
                if (logininfoTem.getType() == 0) {
                  // 得到本次请求的方法对象
                  HandlerMethod handlerMethod = (HandlerMethod) handler;
                  // 从方法对象中的到指定注解
                  PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                  // 判断方法上是否有此注解，如果没有说明是公共资源
                  if(preAuthorize != null){
                    // 从注解中获取到sn值，也就是本次请求对应的权限编码，用于判断用户是否有此URL权限
                    String permissionSn = preAuthorize.sn();
                    // 获取到用户所拥有的所有权限
                    List<String> ownPermissions = permissionMapper.loadOwnPermissionByLogininfoId(logininfoTem.getId());
                    if (!ownPermissions.contains(permissionSn)) {
                      // 员工所有的权限不包含访问的权限，那么直接设置响应信息并拦截
                      PrintWriter writer = response.getWriter();
                      writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                      writer.flush();
                      writer.close();
                      return false;
                    }
                  }
                }
                // 重置时间
                redisTemplate.opsForValue().set("token",logininfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 设置响应字符集
        response.setCharacterEncoding("UTF-8");
        // 设置响应参数类型为JSON
        response.setContentType("application/json;charset=utf-8");
        // 设置响应参数{"success":false;"message":"noLogin"}
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    } */

    /**
    * @Title: preHandle
    * @Description: jwt拦截器
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/14 18:10
    * @Parameters: [request, response, handler]
    * @Return boolean
    */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("3333333333");
        // 获取请求头的消息token
        String token = request.getHeader("token");
        // 判断token是否为空且是否正确
        if (token != null){
            // 解密
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPub).getFile());
            Payload<Userinfo> payload = JwtUtils.getInfoFromToken(token, publicKey, Userinfo.class);
            if (payload != null){
                // 判断登录用户是否有权限
                Userinfo userInfo = payload.getUserInfo();
                Logininfo logininfo = userInfo.getLogininfo();
                // 判断是否是员工
                if (logininfo.getType() == 0) {
                    // 得到本次请求的方法对象
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    // 从方法对象中的到指定注解
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    // 判断方法上是否有此注解，如果没有说明是公共资源
                    if(preAuthorize != null){
                        // 从注解中获取到sn值，也就是本次请求对应的权限编码，用于判断用户是否有此URL权限
                        String permissionSns = preAuthorize.sn();
                        // 获取到用户所拥有的所有权限
                        if (!userInfo.getPermissions().contains(permissionSns)) {
                            // 员工所有的权限不包含访问的权限，那么直接设置响应信息并拦截
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
                // 重置jwt时间
                // redisTemplate.opsForValue().set("token",logininfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 设置响应字符集
        response.setCharacterEncoding("UTF-8");
        // 设置响应参数类型为JSON
        response.setContentType("application/json;charset=utf-8");
        // 设置响应参数{"success":false;"message":"noLogin"}
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    }
}
